package com.jgsu.farm.service.impl;

import com.jgsu.farm.entity.Protection;
import com.jgsu.farm.exception.DataNotExistException;
import com.jgsu.farm.mapper.ProtectionMapper;
import com.jgsu.farm.service.ProtectionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProtectionServiceImpl implements ProtectionService {
    @Autowired
    ProtectionMapper protectionMapper;


    @Override
    public void add(Protection protection) {
        protectionMapper.insert(protection);
    }

    @Override
    public void delete(Integer knowid) {
        Integer id = protectionMapper.deleteByPrimaryKey(knowid);
        if (id == 0 || id == null) {
            throw new DataNotExistException("603", "不存在该id,植保信息删除失败");
        }
    }

    @Override
    public PageInfo<Protection> selectAll(int page, int pagesize) {
        PageHelper.startPage(page, pagesize);
        List<Protection> protections = protectionMapper.selectAll();
        PageInfo<Protection> pageInfoProtectionList = new PageInfo<Protection>(protections);
        return pageInfoProtectionList;
    }


    @Override
    public void update(Protection protection) {
        // 1. 在更新之前根据id查询是否有要查询的数据
        Protection protectionId = protectionMapper.selectByPrimaryKey(protection.getKnowid());
        if (protectionId != null) {
            // 2. 如果有则，更新数据
            protectionMapper.updateByPrimaryKey(protection);
        } else {
            // 3, 如果没有则报错
            throw new DataNotExistException("603", "数据更新失败，不存在相应植保id");
        }
    }


}
